const Router = require('koa-router')
const passport = require('koa-passport')
const formatDate = require('../../utils/dateFormat').formatDate
const router = new Router()
const mongoose = require('mongoose')

const reposOut = require('../../models/RepositoryOut')
const blood = require('../../models/Blood')
const volunteer = require('../../models/Volunteer')
const Repository = require('../../models/Repository')

/**
 * @description test
 */
router.get('/test', async ctx => {
  ctx.body = []
})

/**
 * @description 血液出库
 */
router.post('/ck', async ctx => {
  const body = ctx.request.body
  console.log(body)
  const findResult = await reposOut.find({ blood: mongoose.Types.ObjectId(body.blood) })
  if (findResult.length > 0) {
    ctx.status = 400
    ctx.body = { msg: '已出库' }
  } else {
    const newReposOut = new reposOut({
      outDate: body.outDate,
      blood: mongoose.Types.ObjectId(body.blood),
      claimer: body.claimer,
      claimeDept: body.claimeDept,
      principal: body.principal
    })
    const repositoryDet = await Repository.findById(body.repository)
    const nowStorage = repositoryDet.nowStorage
    await blood.findByIdAndUpdate(body.blood, { isRepos: 2, reposId: body.repository })
    await Repository.findByIdAndUpdate(body.repository, { nowStorage: nowStorage - 1 })
    await newReposOut
      .save()
      .then(res => {
        ctx.body = []
      })
  }
})

/**
 * @description 出库记录查询
 */
router.get('/page', async ctx => {
  const query = ctx.request.query
  let page = Number(query.page) ? Number(query.page) : 1
  let size = Number(query.per_page) ? Number(query.per_page) : 9999
  let skip = (page - 1) * size
  let ReOutNum = query.ReOutNum ? new RegExp(query.ReOutNum) : /[\s\S]*/
  let findResult = await reposOut.find({ isDeleted: 0 }).skip(skip).limit(size)
  console.log('findResult', findResult)
  let totalElement = await reposOut.find({ isDeleted: 0 }).skip(skip).limit(size).countDocuments()
  ctx.status = 200
  ctx.body = {
    current_page: page,
    per_page: size,
    total: totalElement,
    data: findResult
  }
})
/**
 * @description 出库详情
 */
router.get('/get', async ctx => {
  const id = ctx.request.query.id
  console.log('id', id)
  let findResult = await reposOut.aggregate([
    {
      $lookup: {
        from: 'bloods',
        localField: 'blood',
        foreignField: '_id',
        as: 'blood'
      }
    },
    {
      $match: {
        _id: mongoose.Types.ObjectId(id)
        // claimeDept: '妇产科'
      }
    }
  ])
  console.log('findResult', findResult)
  if (findResult) {
    const vId = findResult[0].blood[0].volunteerId
    let findVolunteer = await volunteer.findById(vId)
    if (findVolunteer) {
      ctx.body = {
        _id: findResult[0]._id,
        ReOutNum: findResult[0].ReOutNum,
        outDate: findResult[0].outDate,
        blood: findResult[0].blood[0],
        volunteer: findVolunteer
      }
    } else {
      ctx.status = 400
      ctx.body = []
    }
  }
})

/**
 * @description 删除出库记录
 */
router.get('/delete', async ctx => {
  const id = ctx.request.body.id
  try {
    const updateResult = await reposOut.findByIdAndUpdate(id, { isDeleted: 1 })
    if (updateResult) {
      ctx.status = 200
      ctx.body = []
    } else {
      ctx.status = 400
      ctx.response.status = 400
      ctx.response.message = '数据库中无该条数据'
      ctx.body = {
        msg: '删除失败'
      }
    }
  } catch { }
})
module.exports = router.routes()